<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
use Qcloud\Cos\Client;
require_once "../extend/tencent/vendor/autoload.php";
class Home extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }

    /**
     * 获取about表数据：
     * type：1注册协议 2隐私协议 3功能介绍  4法律声明 5公司logo 6初始网盘内存 7签到送多少积分 8：1M需要多少积分
     * @return string
     */
    public function getAbout()
    {
        extract(input());
        $res = Db::table('up_about')
            ->where('id',$type)
            ->find();
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * location 自动定位返回id：location
     * $location  地区名称
     */
    public function locationGet (){
        extract(input());
        $res = array();
        if(isset($sheng)){
            $shengID = Db::table('up_area')
                ->where('district',$sheng)
                ->where('level',1)
                ->value('district_id');
            $res['sheng'] = $shengID;
        }
        if(isset($shi)){
            $shiID = Db::table('up_area')
                ->where('district',$shi)
                ->where('level',2)
                ->value('district_id');
            $res['shi'] = $shiID;
        }
        if(isset($qu)){
            $quID = Db::table('up_area')
                ->where('district',$qu)
                ->where('level',3)
                ->value('district_id');
            $res['qu'] = $quID;
        }
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 获取首页数据：getHomeData
     * 日历、拜访日期和会议日期
     */
    public function getHomeData(){
        extract(input());
        //1、日历
        if(!isset($month_date) || !$month_date){
            $month_date = date('Y-m-d');
        }

        $rili = $this->getDays7($month_date);
        $meet = Db::table('up_meeting_user')->alias('mu')
            ->join('up_meeting m','mu.mu_m_id=m.m_id','LEFT')
            ->where('mu_user_id',$user_id)
            ->where('mu_status',2)
            ->where('m_del',1)
            ->where('m_day','in',$rili['now'])
            ->where('m_type','in','1,3')
            ->group('m_day')
            ->field('m_day,m_id')
            ->select();
        $user_type = $this->getUserInfo($user_id,'user_type');
        $user_field = 'v_take_uid';
        if($user_type == 2){
            $user_field = 'v_ask_uid';
        }
        $visit = Db::table('up_visit')
            ->where($user_field,$user_id)
            ->where('v_ask_status',2)
            ->where('v_take_status',2)
            ->where('v_day','in',$rili['now'])
            ->group('v_day')
            ->field('v_day,v_id')
            ->select();
        Db::table('up_u_user')->where('user_id',$user_id)->setField('user_logintime',date('Y-m-d H:i:s'));
        //
        $ymdstr = $this->getTodayInfo($month_date);
        return json(['status'=>200,'msg'=>$rili,'meet'=>$meet,'visit'=>$visit,'ymdstr'=>$ymdstr]);
    }

    /**
     * 进入日历
     * 周、月、日程
     * type：1周、2月、3日程
     */
    public function getDatasByType(){
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        $user_field = 'v_take_uid';
        if($user_type == 2){
            $user_field = 'v_ask_uid';
        }
        $order = 'desc';
        if($type == 1){
            if(!isset($month_date) || !$month_date){
                $month_date = date('Y-m-d');
            }
            $rili = $this->getDays7($month_date);
            $ymdstr = $this->getTodayInfo($month_date);
            $where_m = [
                'mu_user_id' => $user_id,
                'm_type' => ['in','1,3'],
                'mu_status' => 2,
                'm_day' => ['in',$rili['now']],
            ];
            $where_v = [
                $user_field => $user_id,
                'v_ask_status' => 2,
                'v_take_status' => 2,
                'v_day' => ['in',$rili['now']],
            ];
        }elseif($type == 2){
            if(!isset($month_date) || !$month_date){
                $month_date = date('Y-m-d');
            }
            $month_month = substr($month_date,0,7);

            $rili = $this->getMonthDays($month_month);

            $ymdstr = $this->getTodayInfo($month_date);
            $where_m = [
                'mu_user_id' => $user_id,
                'm_type' => ['in','1,3'],
                'mu_status' => 2,
                'm_month' => $month_month,
            ];
            $where_v = [
                $user_field => $user_id,
                'v_ask_status' => 2,
                'v_take_status' => 2,
                'v_month' => $month_month,
            ];
        }else{
            if(!isset($month_date) || !$month_date){
                $month_date = date('Y-m-d');
            }
            $rili = '';
            $ymdstr = $this->getTodayInfo($month_date);
            $where_m = [
                'mu_user_id' => $user_id,
                'm_type' => ['in','1,3'],
                'mu_status' => 2,
                'm_day' => $month_date,
            ];
            $where_v = [
                $user_field => $user_id,
                'v_ask_status' => 2,
                'v_take_status' => 2,
                'v_day' => $month_date,
            ];
            if($page < 0){
                $order = 'desc';
                $where_m['m_day'] = ['<',$month_date];
                $where_v['v_day'] = ['<',$month_date];
            }else{
                $order = 'asc';
                $where_m['m_day'] = ['>=',$month_date];
                $where_v['v_day'] = ['>=',$month_date];
            }
            $page = abs($page);
        }
        $field = 'm_id m_v_id,m_type m_v_type,m_update update_time,m_start start,left(m_start,10) start_day,m_end end,m_week week,data_type';
        $meet = Db::table('up_meeting_user')->alias('mu')
            ->join('up_meeting m','mu.mu_m_id=m.m_id','LEFT')
            ->where($where_m)
            ->where('m_del',1)
            ->field($field)
            ->buildSql();
        $field = 'v_id m_v_id,v_type m_v_type,v_update update_time,v_start start,left(v_start,10) start_day,v_end end,v_week week,data_type';
        $visit = Db::table('up_visit')
            ->where($where_v)
            ->field($field)
            ->union([$meet])
            ->buildSql();
        if($type != 3){
            $data = Db::table($visit . ' a')->order("update_time $order")->select();// $c . a是零时表名
        }else{
            $data = Db::table($visit . ' a')->order("update_time $order")->page($page,10)->select();// $c . a是零时表名
        }
        return json(['status'=>200,'msg'=>$data,'rili'=>$rili,'ymdstr'=>$ymdstr]);
    }
    /**
     * 进入日历（切换到月的时候单独拿数据，上面的除了数据 ，还有日期标点 ，所以要单独处理）
     * 月
     */
    public function getDatasByTypeForMonth(){
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        $user_field = 'v_take_uid';
        if($user_type == 2){
            $user_field = 'v_ask_uid';
        }
        if(!isset($month_date) || !$month_date){
            $month_date = date('Y-m-d');
        }
        $order = 'asc';
        $where_m = [
            'mu_user_id' => $user_id,
            'm_type' => ['in','1,3'],
            'mu_status' => 2,
            'm_day' => $month_date,
        ];
        $where_v = [
            $user_field => $user_id,
            'v_ask_status' => 2,
            'v_take_status' => 2,
            'v_day' => $month_date,
        ];
        $field = 'm_id m_v_id,m_type m_v_type,m_update update_time,m_start start,left(m_start,10) start_day,m_end end,m_week week,data_type';
        $meet = Db::table('up_meeting_user')->alias('mu')
            ->join('up_meeting m','mu.mu_m_id=m.m_id','LEFT')
            ->where($where_m)
            ->where('m_del',1)
            ->field($field)
            ->buildSql();
        $field = 'v_id m_v_id,v_type m_v_type,v_update update_time,v_start start,left(v_start,10) start_day,v_end end,v_week week,data_type';
        $visit = Db::table('up_visit')
            ->where($where_v)
            ->field($field)
            ->union([$meet])
            ->buildSql();
        $data = Db::table($visit . ' a')->order("update_time $order")->select();// $c . a是零时表名
        return json(['status'=>200,'msg'=>$data]);
    }

    /**
     * 拜访详情
     * 1、v_ask_uid就看v_ask_status：业务员
     *      1那边同意了但是改了东西，需要我这边同意（操作：同意、拒绝）
     *      2我同意了，要看那边的v_take_status：1对方待接受  2对方已接受  3对方已拒绝；（均无操作）
     *      3我拒绝了（一定是对方改了我没同意），无操作
     * 2、v_take_uid就看v_take_status：医生
     *      1那边发起了申请或者我同意之后对方又改了东西，需要我同意（操作：同意、拒绝）
     *      2我同意了，要看那边的v_ask_status：1业务员待同意  2业务员已同意  3业务员已拒绝;（均无操作）
     *      3我拒绝了；无操作
     */
    public function visitInfo()
    {
        extract(input());
        $field = 'v.*,u1.user_id ask_id,u1.user_username ask_name,u1.user_image ask_image';
        $field .= ',u2.user_id take_id,u2.user_username take_name,u2.user_image take_image';
        $data = Db::table('up_visit')->alias('v')
            ->join('up_u_user u1','v.v_ask_uid=u1.user_id','LEFT')
            ->join('up_u_user u2','v.v_take_uid=u2.user_id','LEFT')
            ->where('v_id',$v_id)
            ->field($field)
            ->find();
        if($data['v_ask_uid'] == $user_id){
            Db::table('up_visit')->where('v_id',$v_id)->setField('v_ask_read',2);
        }else{
            Db::table('up_visit')->where('v_id',$v_id)->setField('v_take_read',2);
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 拜访同意或拒绝
     * v_id
     * status:2同意  3拒绝
     * address
     * start
     * end
     * remark
     */
    public function visitDo()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = Db::table('up_visit')
            ->where('v_id',$v_id)
            ->find();
        $user_username = $this->getUserInfo($user_id,'user_username');
        if($data['v_ask_uid'] == $user_id){ //业务员
            //消息推给医生
            $who = $data['v_take_uid'];
            if($data['v_ask_status'] != 1){
                return json(['status'=>100,'msg'=>'当前状态不可操作']);
            }
            $update = [
                'v_ask_status' => $status,
                'v_take_read' => 1,
                'v_update' => $today
            ];
            if($status == 2){
                $title = '拜访提醒';
                $content = $user_username.'业务员同意了拜访修改，请知悉：';
                if($data['v_start'] != $start || $data['v_end'] != $end || $data['v_address'] != $address){
                    $update['v_take_status'] = 1;
                    $title = '拜访修改提醒';
                    $content = $user_username.'业务员修改了拜访信息，请知悉：';
                }
            }else{
                $title = '拜访提醒';
                $content = $user_username.'业务员拒绝了拜访修改，请知悉：';
            }
        }else{
            //消息推给业务员
            $who = $data['v_ask_uid'];
            if($data['v_take_status'] != 1){
                return json(['status'=>100,'msg'=>'当前状态不可操作']);
            }
            $update = [
                'v_take_status' => $status,
                'v_ask_read' => 1,
                'v_update' => $today
            ];
            if($status == 2) {
                $title = '拜访提醒';
                $content = $user_username.'用户同意了拜访修改，请知悉：';
                if ($data['v_start'] != $start || $data['v_end'] != $end || $data['v_address'] != $address) {
                    $update['v_ask_status'] = 1;
                    $title = '拜访修改提醒';
                    $content = $user_username.'用户修改了拜访信息，请知悉：';
                }
            }else{
                $title = '拜访提醒';
                $content = $user_username.'用户拒绝了拜访修改，请知悉：';
            }
        }
        $update['v_start'] = $start;
        $update['v_end'] = $end;
        $update['v_address'] = $address;
        $update['v_remark'] = $remark;
        $res = Db::table('up_visit')
            ->where('v_id',$v_id)
            ->update($update);
        if($res){
            //
            allInNotice($title,$content,3,$who,$v_id);
            try {
                $this->Jpush(1, $who, $content, ['id' => $v_id,'n_type' => 1]);
            } catch (\Exception $e) {
            }
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>100,'msg'=>'操作失败，请稍后重试']);
        }
    }
    /**
     * 拜访暂缓
     * v_id
     * hold
     */
    public function visitHold()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = Db::table('up_visit')
            ->where('v_id',$v_id)
            ->find();
        if($data['v_ask_uid'] == $user_id){
            $update = [
                'v_ask_hold' => 2,
                'v_update' => $today
            ];
        }else{
            $update = [
                'v_take_hold' => 2,
                'v_update' => $today
            ];
        }
        $res = Db::table('up_visit')
            ->where('v_id',$v_id)
            ->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>100,'msg'=>'操作失败，请稍后重试']);
        }
    }
    /**
     * 拜访结束之后业务员可以编辑客户提问
     * v_id
     * v_question
     */
    public function visitQuestion()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = Db::table('up_visit')
            ->where('v_id',$v_id)
            ->find();
        if($data['v_ask_uid'] == $user_id && $data['v_end'] < $today){
            $update = [
                'v_question' => $v_question
            ];
            Db::table('up_visit')
                ->where('v_id',$v_id)
                ->update($update);
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>100,'msg'=>'当前状态不可操作']);
        }
    }
    /**
     * 拜访结束之后医生可以评价打分
     * v_id
     * v_question
     */
    public function visitComment()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = Db::table('up_visit')
            ->where('v_id',$v_id)
            ->find();
        if($data['v_take_uid'] == $user_id && $data['v_end'] < $today && $data['v_comm_status'] == 1){
            $update = [
                'v_comm_status' => 2,
                'v_comm_content' => $content,
                'v_comm_star' => $star,
            ];
            $res = Db::table('up_visit')
                ->where('v_id',$v_id)
                ->update($update);
            if($res){
                return json(['status'=>200,'msg'=>'操作成功']);
            }else{
                return json(['status'=>100,'msg'=>'操作失败，请稍后重试']);
            }
        }else{
            return json(['status'=>100,'msg'=>'当前状态不可操作']);
        }
    }
    /**
     * 业务员查看拜访记录
     * other_id
     * page
     */
    public function visitHis()
    {
        extract(input());
        $res = Db::table('up_visit')
            ->where('v_ask_uid',$user_id)
            ->where('v_take_uid',$other_id)
            ->order('v_start desc')
            ->page($page,20)
            ->field('v_id,v_start,v_end,v_update')
            ->select();
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 新建拜访
     */
    public function visitAdd()
    {
        extract(input());
        $week_array = ["周日","周一","周二","周三","周四","周五","周六"];
        $today = date('Y-m-d H:i:s');
        $insert = [
            'v_ask_uid' => $user_id,
            'v_take_uid' => $uid,
            'v_type' => $v_type,
            'v_address' => $v_address,
            'v_remark' => $v_remark,
            'v_start' => $v_start,
            'v_end' => $v_end,
            'v_day' => substr($v_start,0,10),
            'v_week' => $week_array[date('w',strtotime($v_start))],
            'v_month' => substr($v_start,0,7),
            'v_del_uids' => ',0,',
            'v_time' => $today,
            'v_update' => $today
        ];
        $canNew = $this->canVisitMeet($user_id,$v_start,$v_end);
        if($canNew == false){
            return json(['status'=>100,'msg'=>'此时间段有未完成的拜访或会议']);
        }else{
            $res = Db::table('up_visit')->insertGetId($insert);
            if($res){
                try {
                    $this->Jpush(1, $uid, '你有一条新的预约拜访消息，去处理', ['id' => $res,'n_type' => 1]);
                } catch (\Exception $e) {
                }
                return json(['status'=>200,'msg'=>'操作成功']);
            }else{
                return json(['status'=>100,'msg'=>'操作失败，请稍后重试']);
            }
        }
    }
    /**
     * 我的所有拜访（待用）
     * page
     */
    public function MyVisit()
    {
        extract(input());
        $res = Db::table('up_visit')
            ->where('v_ask_uid',$user_id)
            ->order('v_start desc')
            ->page($page,20)
            ->field('v_id,v_type,v_start,v_end,v_update')
            ->select();
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 收藏和取消收藏
     * type：1是资料  2是项目  3是会议
     */
    public function likeThree()
    {
        extract(input());
        $have = Db::table('up_like_project')
            ->where('lpro_user_id',$user_id)
            ->where('lpro_type',$type)
            ->where('lpro_prom_id',$id)
            ->find();
        if($have){
            $do = 1;
            $res = Db::table('up_like_project')->where('lpro_id',$have['lpro_id'])->delete();
        }else{
            $do = 2;
            $data = [
                'lpro_user_id' => $user_id,
                'lpro_type' => $type,
                'lpro_prom_id' => $id,
                'lpro_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_like_project')->insert($data);
        }
        if($res){
            return json(['status'=>200,'msg'=>'操作成功','dotype'=>$do]);
        }else{
            return json(['status'=>100,'msg'=>'操作失败','dotype'=>$do]);
        }

    }
    /**
     * 删除收藏
     */
    public function deleteLike()
    {
        extract(input());
        $res = Db::table('up_like_project')->where('lpro_id','in',$lpro_id)->delete();
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>100,'msg'=>'操作失败']);
        }

    }

    /**
     * 生成省市区json数据：makeJson
     * @return string
     */
    public function makeJson()
    {
//        set_time_limit(0);
//        $area = file_get_contents('static/area.json');
//        $area2 = json_decode($area,true);
//        return json($area2);
        set_time_limit(0);
        $pro = Db::table('up_area')
            ->where('pid',0)
//            ->where('district_id',1001)
            ->field('district_id id,district name')
            ->order('sort')
            ->select();
        foreach($pro as $k=>$v){
            $pro[$k]['parentId'] = 0;
            $city = Db::table('up_area')
                ->where('pid',$v['id'])
                ->where('level',2)
                ->field('district_id id,district name,pid parentId')
                ->select();
//            foreach ($city as $kk=>$vv){
//                $city[$kk]['sub'] = Db::table('up_area')
//                    ->where('pid',$vv['id'])
//                    ->where('level',3)
//                    ->field('district_id id,district name,pid parentId')
//                    ->select();
//            }
            $pro[$k]['sub'] = $city;
        }
        return json($pro);
    }
}